<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { loginService, getClassesAndColleges, getClassesByCollegeId, registerService } from '@/api/login.js'

const registerData = ref({
  username: '',
  password: '',
  email: '',
  classId: '',
  collegeId: '',
  studentId: '',
  phone: '',
  gender: ''
})

const loginData = ref({
  username: '',
  password: ''
})

const isRegister = ref(false)
const loading = ref(false)
const form = ref(null)

const router = useRouter()
const userStore = useUserStore()

const login = async () => {
  try {
    await form.value.validate()
    loading.value = true
    const resp = await loginService(loginData.value)
    loading.value = false
    ElMessage.success('登录成功')

    userStore.setStatus(resp.data.status)
    userStore.setUserId(resp.data.userId)
    userStore.setUserName(resp.data.username)

    if (resp.data.status === 1) {
      router.push('/admin/manage')
    } else {
      router.push('/index')
    }
  } catch (err) {
    loading.value = false
    ElMessage.error('登录失败，请检查用户名或密码')
    console.error('Login error:', err)
  }
}

// 清除表单数据
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    email: '',
    classId: '',
    collegeId: '',
    studentId: '',
    phone: '',
    gender: ''
  }
}

// 获取学院和班级信息
const colleges = ref([])
const classes = ref([])
const selectedCollegeId = ref(null)
const selectedClassId = ref(null)

const loadClassesAndColleges = async () => {
  try {
    const resp = await getClassesAndColleges()
    console.log('Colleges and classes response:', resp.data) // 调试信息
    colleges.value = resp.data.colleges
    classes.value = resp.data.classes
  } catch (err) {
    ElMessage.error('获取班级和学院信息失败')
    console.error(err)
  }
}

const onCollegeChange = async (collegeId) => {
  console.log('Selected college ID:', collegeId) // 调试信息
  try {
    const resp = await getClassesByCollegeId(collegeId)
    console.log('Classes response:', resp.data) // 调试信息
    classes.value = resp.data
    selectedClassId.value = null // 重置班级选择
    registerData.value.collegeId = collegeId // 同步到 registerData
  } catch (err) {
    ElMessage.error('获取班级信息失败')
    console.error(err)
  }
}

const toggleRegisterForm = () => {
  isRegister.value = true
  loadClassesAndColleges() // 切换到注册表单时加载班级和学院信息
}

// 定义表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 5, message: '用户名长度在2到5位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度在5到16位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮件', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮件', trigger: 'blur' }
  ],
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[123456789]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
}

// 实现注册
const register = async () => {
  try {
    await form.value.validate() // 校验表单
    loading.value = true // 显示加载状态

    // 调用注册 API
    const resp = await registerService(registerData.value)
    loading.value = false
    ElMessage.success('注册成功')
    router.push("/login");
    isRegister.value = false
    // 注册成功后可以进行跳转
    
  } catch (err) {
    loading.value = false
    ElMessage.error('注册失败，请检查表单信息（用户名已存在）')
    console.error('Register error:', err)
  }
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="ElMenu" placeholder="请输入电子邮件" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="studentId">
          <el-input :prefix-icon="User" placeholder="请输入学号" v-model="registerData.studentId"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input :prefix-icon="User" placeholder="请输入手机号" v-model="registerData.phone"></el-input>
        </el-form-item>
        <el-form-item prop="gender">
          <div>性别：</div>
          <el-radio-group v-model="registerData.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="collegeId">
          <el-select v-model="registerData.collegeId" placeholder="请选择学院" @change="onCollegeChange">
            <el-option v-for="college in colleges" :key="college.collegeId" :label="college.name" :value="college.collegeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="classId">
          <el-select v-model="registerData.classId" placeholder="请选择班级" :disabled="!classes.length">
            <el-option v-for="classItem in classes" :key="classItem.classId" :label="classItem.name" :value="classItem.classId"></el-option>
          </el-select>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button orange-button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="loginData">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="loginData.password"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button orange-button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="toggleRegisterForm">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/logo.png') no-repeat 50% center / 540px auto,
    url('@/assets/login_bg.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
